﻿using IntelligentStorWpfApp.Controller;
using IntelligentStorWpfApp.Model;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media;

namespace IntelligentStorWpfApp.View
{
    /// <summary>
    /// Register.xaml 的交互逻辑
    /// </summary>
    public partial class Register : Window
    {
        private bool checkUserId = false;       // 校验用户名
        private bool checkPwd = false;          // 校验密码
        private bool checkRepwd = false;        // 校验确认密码
        private UserController userControl;
        private List<User> userlist;
        private static readonly ILog log = LogManager.GetLogger(typeof(Register));
        public Register()
        {
            InitializeComponent();
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
        }

        private void Register_Loaded(object sender, RoutedEventArgs e)
        {
            userControl = new UserController();
            userlist = new List<User>();
            // 校验用户名
            m_txt_user.LostFocus += M_txt_user_LostFocus;
            // 校验密码
            m_txt_pwd.LostFocus += Pwd_LostFocus;
            // 校验两次密码是否一致
            m_txt_pwdConfirm.LostFocus += Repwd_LostFocus;
        }

        #region 校验用户名
        // 校验用户名：a~z、A~Z、0~9，6~20个字符
        private void M_txt_user_LostFocus(object sender, RoutedEventArgs e)
        {
            checkUserId = false;
            string userId = m_txt_user.Text.Trim();
            if (string.IsNullOrEmpty(userId))
            {
                userIdCheck.Text = "用户名不能为空";
                userIdCheck.Foreground = Brushes.Red;
                return;
            }

            // 判断长度：6~20个字符
            if (userId.Length < 6 || userId.Length > 20)
            {
                userIdCheck.Text = "长度6~20个字符";
                userIdCheck.Foreground = Brushes.Red;
                return;
            }

            // 判断格式：a~z、A~Z、0~9
            string pattern = @"^[0-9a-zA-Z]+$";
            if (!Regex.IsMatch(userId, pattern))
            {
                userIdCheck.Text = "仅限数字和字母";
                userIdCheck.Foreground = Brushes.Red;
                return;
            }

            /*
             * 自定义的联网函数。联网判断用户名是否已存在。
             * 参数：用户名，校验成功的回调，校验失败的回调
             */
            //appDataService.ConfirmUser(userId, ConfirmUserSuccess, ConfirmUserFail);
            userlist = userControl.getAllUsers();
            List<User> tempuser = userlist.Where(u => u.UserName.Equals(userId)).ToList();
            if(tempuser.Count>0)
            {
                ConfirmUserFail("用户名已存在!");
                
            }
            else
            {
                ConfirmUserSuccess("√");
            }
        }

        // 当前输入的用户名可用
        private void ConfirmUserSuccess(string msg)
        {
            userIdCheck.Text = msg;
            userIdCheck.Foreground = Brushes.Green;
            checkUserId = true;
        }

        // 当前输入的用户名不可用，因为已存在
        private void ConfirmUserFail(string msg)
        {
            userIdCheck.Text = msg;
            userIdCheck.Foreground = Brushes.Red; checkUserId = true;
        }
        #endregion

        #region 校验密码
        // 校验密码：a~z、A~Z、0~9，6~20个字符
        private void Pwd_LostFocus(object sender, RoutedEventArgs e)
        {
            checkPwd = false;
            string pwd = m_txt_pwd.Password;
            if (string.IsNullOrEmpty(pwd))
            {
                txtcheckPwd.Text = "密码不能为空";
                txtcheckPwd.Foreground = Brushes.Red;
                return;
            }

            // 判断长度：6~20个字符
            if (pwd.Length < 6 || pwd.Length > 20)
            {
                txtcheckPwd.Text = "长度6~20个字符";
                txtcheckPwd.Foreground = Brushes.Red;
                return;
            }

            // 判断格式：a~z、A~Z、0~9
            string pattern = @"^[0-9a-zA-Z]+$";
            if (!Regex.IsMatch(pwd, pattern))
            {
                txtcheckPwd.Text = "仅限数字和字母";
                txtcheckPwd.Foreground = Brushes.Red;
                return;
            }

            // 符合以上所有要求
            txtcheckPwd.Text = "√";
            txtcheckPwd.Foreground = Brushes.Green;
            checkPwd = true;
        }
        #endregion

        #region 校验两次密码是否一致
        // 校验两次密码是否一致
        private void Repwd_LostFocus(object sender, RoutedEventArgs e)
        {
            checkRepwd = false;
            string pwd = m_txt_pwd.Password;
            string repwd = m_txt_pwdConfirm.Password;
            if (string.IsNullOrEmpty(repwd))
            {
                checkConfirmPwd.Text = "";
                return;
            }

            if (!pwd.Equals(repwd))
            {
                checkConfirmPwd.Text = "两次密码不一致";
                checkConfirmPwd.Foreground = Brushes.Red;
                checkRepwd = false;
            }
            else
            {
                checkConfirmPwd.Text = "√";
                checkConfirmPwd.Foreground = Brushes.Green;
                checkRepwd = true;
            }

        }
        #endregion



        private void m_bt_OK_Click(object sender, RoutedEventArgs e)
        {
            // 判断注册信息是否填写正确、完整
            M_txt_user_LostFocus(null, null);
            Pwd_LostFocus(null, null);
            Repwd_LostFocus(null, null);

            bool checkInfo = checkUserId && checkPwd && checkRepwd;
            if (!checkInfo)
            {
                MessageBox.Show("请检查注册信息是否填写正确、完整!");
                return;
            }

            // 注册
            try
            {
                string userId = m_txt_user.Text.Trim();
                string pwd = m_txt_pwd.Password;
                User currentUser = new User();
                currentUser.UserName = userId;
                currentUser.UserPwd = pwd;
                currentUser.FaceId = App.user.FaceId;


                /* 
                  * 自定义的联网函数。联网判断用户名是否已存在。 
                  * 参数：用户名，昵称，密码，性别，校验成功的回调，校验失败的回调 
                  */
                bool result = userControl.AddUser(currentUser);
                if (result)
                {
                    MessageBox.Show("用户" + userId + "注册成功!","Info",MessageBoxButton.OK,MessageBoxImage.Information);
                    this.Close();
                }
                else
                {
                    MessageBox.Show("用户" + userId + "注册失败!","Error",MessageBoxButton.OK,MessageBoxImage.Error);
                    return;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Register_Closed(object sender, EventArgs e)
        {
            App.user = null;
            Login loginwin = new Login();
            loginwin.Show();
        }

        private void m_bt_reset_Click(object sender, RoutedEventArgs e)
        {
            m_txt_user.Text = "";
            userIdCheck.Text = "";
            m_txt_pwd.Password = "";
            txtcheckPwd.Text = "";
            m_txt_pwdConfirm.Password = "";
            checkConfirmPwd.Text = "";

        }
    }
}
